package com.atguigu.digest;

import com.sun.org.apache.xml.internal.security.utils.Base64;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.security.MessageDigest;

/**
 * DigestDemo1
 *
 * @Author: 马伟奇
 * @CreateTime: 2021-02-27
 * @Description:
 */
public class DigestDemo1 {
    public static void main(String[] args) throws Exception{
        // 定义原文
        // kAFQmDzST7DWlj99KOF/cg==
        // 900150983cd24fb0d6963f7d28e17f72
        // 900150983cd24fb0d6963f7d28e17f72
        String input = "abc";
        // 获取数字摘要对象
        String algorithm = "md5";
        // 55ca12f5f9c61057c1eca53501af2c0f33546c91
        // 55ca12f5f9c61057c1eca53501af2c0f33546c91
        // 7233757ecb622f520f81a10bf4c0e8e1f1e3fb8a
        String sha1 = getDigestFile("aaa.txt", "SHA-1");
        System.out.println(sha1);

        // 获取数字摘要对象
//        String md5 = getDigest(input, "MD5");
//        System.out.println(md5);
//
//        String sha1 = getDigest(input, "SHA-1");
//        System.out.println(sha1);
//
//        String sha256 = getDigest(input, "SHA-256");
//        System.out.println(sha256);
//
//        String sha512 = getDigest(input, "SHA-512");
//        System.out.println(sha512);
    }

    private static String getDigestFile(String path, String algorithm) throws Exception{
        FileInputStream fis = new FileInputStream(path);
        byte[] buffer =  new byte[1024];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len;
        while ((len = fis.read(buffer))!=-1){
            baos.write(buffer,0,len);
        }
        MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
        byte[] bytes = messageDigest.digest(baos.toByteArray());

        return toHex(bytes);
    }

    private static String toHex(byte[] digest) throws Exception {

//        System.out.println(new String(digest));
        // base64编码
//        System.out.println(Base64.encode(digest));
        // 创建对象用来拼接
        StringBuilder sb = new StringBuilder();

        for (byte b : digest) {
            // 转成 16进制
            String s = Integer.toHexString(b & 0xff);
            if (s.length() == 1){
                // 如果生成的字符只有一个，前面补0
                s = "0"+s;
            }
            sb.append(s);
        }
        System.out.println("16进制数据的长度：" + sb.toString().getBytes().length);
        return sb.toString();
    }

    private static String getDigest(String input, String algorithm) throws Exception {
        MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
        // 消息数字摘要
        byte[] digest = messageDigest.digest(input.getBytes());
        System.out.println("密文的字节长度:" + digest.length);

        return toHex(digest);
    }
}